package com.warom.sdg.webview.jsinterface;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.webkit.JavascriptInterface;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.warom.sdg.dto.PageRequestDto;
import com.warom.sdg.service.OperationLogService;
import com.warom.sdg.util.UserPreferencesManager;
import com.warom.sdg.webview.BaseWebViewJsInterface;
import com.warom.sdg.webview.WebViewWrapper;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.Map;

// 导入用户管理接口，用于获取当前登录用户信息
import com.warom.sdg.webview.jsinterface.WebViewJsUserManagerInterface;

/**
 * 操作日志JavaScript接口
 */
public class WebViewJsOperationLogInterface extends BaseWebViewJsInterface {
    private static final String TAG = "OperationLogJsInterface";
    private final Handler mHandler = new Handler(Looper.getMainLooper());
    private final Gson gson = new Gson();
    private final ExecutorService executor = Executors.newSingleThreadExecutor();
    
    private OperationLogService operationLogService;
    private WebViewWrapper webViewWrapper;

    /**
     * 构造函数
     * @param context 上下文
     */
    public WebViewJsOperationLogInterface(Context context) {
        super(context, null);
        this.operationLogService = new OperationLogService(context);
    }

    /**
     * 构造函数
     * @param context 上下文
     * @param webViewWrapper WebView包装器
     */
    public WebViewJsOperationLogInterface(Context context, WebViewWrapper webViewWrapper) {
        super(context, webViewWrapper);
        this.webViewWrapper = webViewWrapper;
        this.operationLogService = new OperationLogService(context);
    }

    // /**
    //  * 记录操作日志
    //  * @param args 参数JSON字符串
    //  * @param requestId 请求ID
    //  */
    // @JavascriptInterface
    // public void logOperation(String args, String requestId) {
    //     executor.execute(() -> {
    //         try {
    //             Map<String, String> params = gson.fromJson(args, new TypeToken<Map<String, String>>(){}.getType());
                
    //             // 从参数中获取用户名，如果为空或为"unknown"，则使用当前登录用户
    //             String username = params.get("username");
    //             if (username == null || username.isEmpty() || "unknown".equals(username)) {
    //                 username = UserPreferencesManager.getCurrentUsername(context);
    //                 if (username == null) {
    //                     username = "未知用户";
    //                 }
    //             }
                
    //             String operationType = params.get("operationType");
    //             String operationDescription = params.get("operationDescription");
    //             String operationPage = params.get("operationPage");
    //             String operationTarget = params.get("operationTarget");
    //             String operationStatus = params.get("operationStatus");
    //             String errorMessage = params.get("errorMessage");
                
    //             operationLogService.logOperation(username, operationType, operationDescription, 
    //                 operationPage, operationTarget, operationStatus, errorMessage);
                
    //             handleAsyncResponse(requestId, "{\"success\":true,\"message\":\"操作日志记录成功\"}");
    //         } catch (Exception e) {
    //             Log.e(TAG, "记录操作日志失败", e);
    //             handleAsyncResponse(requestId, "{\"success\":false,\"message\":\"" + e.getMessage() + "\"}");
    //         }
    //     });
    // }

    /**
     * 记录设备控制操作日志
     * @param args 参数JSON字符串
     * @param requestId 请求ID
     */
    @JavascriptInterface
    public void logDeviceControl(String args, String requestId) {
        executor.execute(() -> {
            try {
                Map<String, String> params = gson.fromJson(args, new TypeToken<Map<String, String>>(){}.getType());
                
                // 从参数中获取用户名，如果为空或为"unknown"，则使用当前登录用户
                String username = params.get("username");
                if (username == null || username.isEmpty() || "unknown".equals(username)) {
                    username = UserPreferencesManager.getCurrentUsername(context);
                    if (username == null) {
                        username = "未知用户";
                    }
                }
                
                String deviceName = params.get("deviceName");
                String action = params.get("action");
                String status = params.get("status");
                String errorMessage = params.get("errorMessage");
                
                operationLogService.logDeviceControl(username, deviceName, action, status, errorMessage);
                
                handleAsyncResponse(requestId, "{\"success\":true,\"message\":\"设备控制操作日志记录成功\"}");
            } catch (Exception e) {
                Log.e(TAG, "记录设备控制日志失败", e);
                handleAsyncResponse(requestId, "{\"success\":false,\"message\":\"" + e.getMessage() + "\"}");
            }
        });
    }

    /**
     * 获取操作日志列表（分页）
     * @param args 参数JSON字符串
     * @param requestId 请求ID
     */
    @JavascriptInterface
    public void getOperationLogs(String args, String requestId) {
        executor.execute(() -> {
            try {
                // 解析参数为PageRequestDto对象
                PageRequestDto pageRequest = gson.fromJson(args, PageRequestDto.class);
                
                // 获取分页参数，并确保它们在有效范围内
                int page = pageRequest.getPage(); // 已在DTO中处理默认值
                int pageSize = pageRequest.getPageSize(); // 已在DTO中处理默认值
                
                // 设置最大页面大小限制，避免请求过大数据量
                if (pageSize > 50) {
                    pageSize = 50;
                }
                
                Log.d(TAG, "获取操作日志: " + pageRequest.toString());
                
                // 调用服务获取日志
                String result = operationLogService.getOperationLogs(page, pageSize);
                handleAsyncResponse(requestId, result);
            } catch (Exception e) {
                Log.e(TAG, "获取操作日志列表失败", e);
                handleAsyncResponse(requestId, "{\"success\":false,\"message\":\"" + e.getMessage() + "\"}");
            }
        });
    }
} 